<template>
	<view>
		<!-- 学生部分 -->
		<u-form labelPosition="left" :model="model1" ref="uForm" v-show="studentShow">

			<u-form-item label="" prop="model1.userInfo.image" borderBottom>
				<image :src="model1.userInfo.image" class="uploadImge" @click="chooseAndUploadImage()"></image>
				<view style="margin-left:86%;font-size: 50px;color: aqua;cursor: pointer;" @click="backToFirst()"><-</view>
			</u-form-item>
			<u-form-item label="学号" prop="userInfo.workId" borderBottom>
				<text> {{ model1.userInfo.workId }} </text>
			</u-form-item>

			<u-form-item label="专业" prop="userInfo.major" borderBottom>
				<text>{{ model1.userInfo.major }}</text> </u-form-item>

			<u-form-item label="班级" prop="userInfo.stuClass" borderBottom>
				<text>{{ model1.userInfo.major }}</text> </u-form-item>
			<u-form-item label="性别" prop="userInfo.sex" borderBottom>
				<text>{{ model1.userInfo.sex }}</text> </u-form-item>
			<u-form-item label="学院" prop="userInfo.college" borderBottom>
				<text>{{ model1.userInfo.college }}</text> </u-form-item>
			<u-form-item label="家庭住址" prop="userInfo.address" borderBottom>
				<u-input v-model="model1.userInfo.address" style="border: 1px solid #ccc;"></u-input>
			</u-form-item>
			<u-form-item label="联系方式" prop="userInfo.contact" borderBottom>
				<u-input v-model="model1.userInfo.contact" style="border: 1px solid #ccc;"></u-input>
			</u-form-item>
			<u-form-item label="个性签名" prop="userInfo.signature" borderBottom>
				<u-input v-model="model1.userInfo.signature" style="border: 1px solid #ccc;"></u-input>
			</u-form-item>

		</u-form>

		<!-- 教师部分 -->

		<u-form labelPosition="left" :model="model1" ref="uForm" v-show="teacherShow">

			<u-form-item label="" prop="model1.userInfo.image" borderBottom>
				<image :src="model1.userInfo.image" class="uploadImge" @click="chooseAndUploadImage()"></image>
			</u-form-item>
			<u-form-item label="工号:" prop="userInfo.workId" borderBottom>
				<text> {{ model1.userInfo.workId }} </text>
			</u-form-item>

			<u-form-item label="办公室:" prop="userInfo.office" borderBottom>
				<text> {{ model1.userInfo.workId }} </text>
			</u-form-item>

			<u-form-item label="性别" prop="userInfo.sex" borderBottom>
				<text>{{ model1.userInfo.sex }}</text> </u-form-item>
			<u-form-item label="学院" prop="userInfo.college" borderBottom>
				<text>{{ model1.userInfo.college }}</text> </u-form-item>

			<u-form-item label="联系方式" prop="userInfo.contact" borderBottom>
				<u-input v-model="model1.userInfo.contact" style="border: 1px solid #ccc;"></u-input>
			</u-form-item>
			<u-form-item label="个性签名" prop="userInfo.signature" borderBottom>
				<u-input v-model="model1.userInfo.signature" style="border: 1px solid #ccc;"></u-input>
			</u-form-item>

		</u-form>


		<!-- 管理员部分 -->

		<u-form labelPosition="left" :model="model1" ref="uForm" v-show="adminShow">

			<u-form-item label="头像" prop="model1.userInfo.image" borderBottom>
				<image :src="model1.userInfo.image" class="uploadImge" @click="chooseAndUploadImage()"></image>
				<view style="margin-left:86%;font-size: 50px;color: aqua;cursor: pointer;" @click="backToFirst()"><-</view>
			</u-form-item>
			<u-form-item label="工号" prop="userInfo.workId" borderBottom>
				<text> {{ model1.userInfo.workId }} </text>
			</u-form-item>

			<u-form-item label="性别" prop="userInfo.sex" borderBottom>
				<text>{{ model1.userInfo.sex }}</text> </u-form-item>

			<u-form-item label="联系方式" prop="userInfo.contact" borderBottom>
				<u-input v-model="model1.userInfo.contact" style="border: 1px solid #ccc;"></u-input>
			</u-form-item>
			<u-form-item label="个性签名" prop="userInfo.signature" borderBottom>
				<u-input v-model="model1.userInfo.signature" style="border: 1px solid #ccc;"></u-input>
			</u-form-item>
		</u-form>


		<view style="display: flex; justify-content:center">
			<view style="display: flex; justify-content: flex-start; padding: 10px 0;">
				<u-button type="primary" text="保存" :plain="true" style="width: 100px; margin-left: 0;"
					@click="updateInfoFun()"></u-button>
			</view>
			<!-- 修改密码按钮，使用 flexbox 保证左对齐 -->
			<view style="display: flex; justify-content: flex-start; padding: 10px 0;">
				<u-button type="primary" text="修改密码" :plain="true" style="width: 100px; margin-left: 0;"
					@click="editPasswordShow=true"></u-button>
			</view>
		</view>


		<!-- 修改密码 -->
		<view>
			<u-popup :show="editPasswordShow" mode="center" @close="close" @open="open">
				<view style="width: 300px;height: 200px;" class="uppo">
					<view>
						<view style="padding-left: 35px;padding-top: 20px;">修改密码</view>

						<view style="display: flex;padding-left: 3px;padding-top: 17px;">
							<u-input placeholder="请输入原密码" border="surround" v-model="oldPassword"></u-input>
						</view>
					</view>

					<view style="display: flex;padding-left: 3px;padding-top: 17px;">
						<u-input placeholder="请输入新密码" border="surround" v-model="newPassword"></u-input>
					</view>

					<view>
						<u-button text="确认" @click="updateInfoFun()"></u-button>
					</view>
				</view>
			</u-popup>
		</view>


	</view>
</template>

<script>
	import Own from "../../api/util/index.js"
	export default {
		data() {
			return {
				model1: {
					userInfo: {
						id: null, // 主键id
						college: '', // 学院
						major: '', // 专业
						office: '', //办公室
						enrollmentYear: '', //入学年份
						stuClass: '', //班级
						contact: '', // 手机号
						enrollmentYear: '', // 入学年份
						userId: null, // 用户id
						workId: '', // 工号
						address: '', // 家庭住址
						image: '', // 头像
						signature: '', // 个性签名
						sex: '', // 性别
						identity: 0,
					},

				},
				editPasswordShow: false,
				oldPassword: '',
				newPassword: '',
				studentShow: false,
				teacherShow: true,
				adminShow: false


			};
		},
		methods: {
			close() {
				this.editPasswordShow = false
			},


			async updateInfoFun() {
				try {
					let editInfo = {
						address: this.model1.userInfo.address, // 家庭住址
						image: this.model1.userInfo.image, // 头像
						signature: this.model1.userInfo.signature, // 个性签名
						contact: this.model1.userInfo.contact, // 手机号
						password: this.oldPassword, // 原密码
						newPassword: this.newPassword // 新密码
					};
					// 移除了多余的逗号
					let responseEdit = await Own.updateInfo(editInfo); // 注意 responseEdit 拼写正确
					alert("修改信息成功")
					this.editPasswordShow = false
				} catch (error) {
					alert("修改信息失败")
					console.error(error); // 建议在捕获异常时打印错误信息，方便调试
				}
			},

			sexSelect(e) {
				this.model1.userInfo.sex = e.name
				this.$refs.uForm.validateField('userInfo.sex')
			},

			async getInfo() { // 定义为异步方法
				try {
					const res = await Own.getOwnInfo();
					this.model1.userInfo = res.data;

					if (this.model1.userInfo.identity === 0) {
						this.studentShow = true
						this.teacherShow = false
						this.adminShow = false
					} else if (this.model1.userInfo.identity === 1) {
						this.studentShow = false
						this.teacherShow = true
						this.adminShow = false
					} else if (this.model1.userInfo.identity === 2) {
						this.studentShow = false
						this.teacherShow = false
						this.adminShow = true
					}

					console.log(this.model1.userInfo.id);
					console.log(this.model1.userInfo);
				} catch (error) {
					console.error("Error:", error);
				}
			},

			async chooseAndUploadImage() {
				try {
					// 显示加载提示
					uni.showLoading({
						title: '正在选择图片',
						mask: true
					});

					// 使用 uni.chooseImage 选择图片
					const chooseRes = await uni.chooseImage({
						count: 1, // 允许选择的图片数量
						sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'] // 可以指定来源是相册还是相机，默认二者都有
					});
					console.log('chooseRes', chooseRes)
					console.log('路径', chooseRes[1].tempFilePaths[0])
					// if (tempFilePaths.length === 0) {
					//   console.warn('没有选择任何文件');
					//   return;
					// }

					// 使用 uni.uploadFile 上传图片
					const uploadRes = await this.uploadFile(chooseRes[1].tempFilePaths[0]);

					console.log(uploadRes)
					// 设置图片 URL 到 data 中
					this.model1.userInfo.image = uploadRes.data
					this.updateInfoFun()
					this.getInfo()
					console.log(231)
					// 隐藏加载提示
					uni.hideLoading();
					uni.showToast({
						title: '图片上传成功',
						icon: 'success'
					});

				} catch (error) {
					console.error('处理上传图片时发生错误:', error);
					uni.hideLoading();
					uni.showToast({
						title: '处理上传图片时发生错误',
						icon: 'none'
					});
				}
			},
			async uploadFile(filePath) {
				try {
					// 显示加载提示
					uni.showLoading({
						title: '正在上传图片',
						mask: true
					});

					// 调用 uni.uploadFile 上传图片
					const res = await new Promise((resolve, reject) => {
						uni.uploadFile({
							url: 'http://localhost:8185/news/uploadImage', // 开发者服务器 url
							filePath: filePath, // 要上传文件资源的路径
							name: 'file', // 文件对应的 key
							success: (uploadRes) => {
								resolve(uploadRes);
							},
							fail: (err) => {
								reject(err);
							}
						});
					});

					// 解析 JSON 响应
					const responseData = JSON.parse(res.data);

					if (responseData.code == 200) {
						return responseData; // 返回解析后的响应数据
					} else {
						throw new Error(`上传失败: ${responseData}`);
					}
				} catch (error) {
					console.error('上传图片失败:', error);
					throw error;
				} finally {
					// 确保隐藏加载提示
					uni.hideLoading();
				}
			},
			backToFirst() {
				if (this.model1.userInfo.identity === 0) {
					uni.navigateTo({
						url: '/pages/stuIndex/stuIndex',
					});
				} else if (this.model1.userInfo.identity === 1) {
					uni.switchTab({
						url: '/pages/index/index',
					});
				} else {
					uni.navigateTo({
						url: '/pages/adminIndex/adminIndex',
					});
				}
			},
			

		},
		async onLoad() {
			// 在 Vue 生命周期中调用 getInfo 方法
			await this.getInfo();
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			// this.$refs.uForm.setRules(this.rules)
		},
	};
</script>

<style>
	.uploadImge {
		width: 180rpx;
		height: 180rpx;
		border-radius: 20rpx;
		background-color: #f4f4f5;
		display: flex;
		justify-content: center;
		align-items: center;
		text-align: center;
		color: #909399;
	}
</style>